<template>
	<el-dialog v-model="dialogVisible" width="800px" :title="userId ? '修改用户' : '新增用户'">
		<template #default>
			<el-form :model="userForm" label-width="90px" class="user-editor-form">
				<el-form-item label="用户名" prop="username" class="inline">
					<el-input v-model="userForm.username" show-word-limit placeholder="请输入用户名" />
				</el-form-item>

				<el-form-item label="密码" prop="password" class="inline" v-if="!userForm.id">
					<el-input type="password" v-model="userForm.password" show-word-limit placeholder="请输入用户密码" />
				</el-form-item>

				<el-form-item label="真实姓名" prop="realName" class="inline">
					<el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
				</el-form-item>

				<el-form-item label="邮箱" prop="email" class="inline">
					<el-input v-model="userForm.email" placeholder="请输入邮箱" />
				</el-form-item>

				<el-form-item label="性别" prop="gender" class="inline">
					<el-select v-model="userForm.gender" placeholder="请选择性别">
						<el-option v-for="item in dicts.system_global_gender" :key="item.v" :label="item.k"
							:value="userForm.gender == item.v ? userForm.gender : item.v">
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="手机号码" prop="phone" class="inline">
					<el-input v-model="userForm.phone" placeholder="请输入手机号码" />
				</el-form-item>

				<el-form-item label="启用状态" prop="enabled" class="inline">
					<el-radio-group v-model="userForm.enabled">
						<el-radio v-for="item in dicts.system_global_status" :key="item.v"
							:label="userForm.enabled == item.v ? userForm.enabled : item.v" :value="item.v">
							{{ item.k }}
						</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="所属机构" prop="unitId" class="inline">
					<el-tree-select class="treeList" v-model="userForm.unitId" placeholder="请选择所属机构"
						:render-after-expand="false" :data="unitTree" :props="{ label: 'name' }" :check-strictly="true"
						:auto-expand-parent="true" :default-expand-all="true" node-key="id" />
				</el-form-item>

				<el-form-item label="所属岗位" prop="postIds" class="inline">
					<el-tree-select class="treeList" v-model="userForm.postIds" placeholder="请选择所属岗位"
						:render-after-expand="false" :data="postTree" :props="{ label: 'postName' }"
						:auto-expand-parent="true" :default-expand-all="true" node-key="id" show-checkbox multiple />
				</el-form-item>

				<el-form-item label="分配角色" prop="roleIds" class="inline">
					<el-tree-select class="treeList" v-model="userForm.roleIds" placeholder="请选择分配角色"
						:render-after-expand="false" :data="roleTree" :props="{ label: 'roleName' }"
						:auto-expand-parent="true" :default-expand-all="true" node-key="id" show-checkbox multiple />
				</el-form-item>

				<el-form-item label="备注">
					<el-input type="textarea" placeholder="请输入备注内容" v-model='userForm.remark' :maxlength="200"
						show-word-limit></el-input>
				</el-form-item>

			</el-form>
		</template>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { getRolePageApi } from '@renderer/api/role';
import { getPostPageApi, getUnitListApi, getUserGetApi, postUserAOUApi } from '@renderer/api/user';
import { useDicts } from '@renderer/composables/dicts';
import { Role } from '@renderer/interface/role';
import { Post, Unit } from '@renderer/interface/user';
import { onMounted, reactive, ref, watch } from 'vue';

/* 父组件传参 */
const props = defineProps<{
	userId: string
}>()
const emits = defineEmits(['userSuccess'])
const dialogVisible = defineModel({ default: false })

/* 表单数据 */
const userFormValue = (): any => ({
	id: undefined,
	username: '',
	password: '',
	realName: '',
	email: '',
	gender: '',
	phone: '',
	enabled: '',
	unitId: '',
	postIds: [],
	roleIds: [],
	remark: ''
})
const userForm = reactive(userFormValue())
const { dicts } = useDicts(['system_global_gender', 'system_global_status'])
// 获取用户详情信息
const getUserGetData = async () => {
	const { code, data: { user, postIds, roleIds } } = await getUserGetApi(props.userId)
	if (code !== '200') return

	Object.assign(userForm, user)
	userForm.postIds = postIds
	userForm.roleIds = roleIds
}
// 机构树
const unitTree = ref<Unit[]>([])
// 岗位树
const postTree = ref<Post[]>([])
// 角色树
const roleTree = ref<Role[]>([])
// 拉取信息
const getTreeData = async () => {
	const res = await Promise.all([getUnitListApi(), getPostPageApi(), getRolePageApi()])
	const [{ code: unitCode, data: unitData }, { code: postCode, data: { records: postRecords } }, { code: roleCode, data: { records: roleRecords } }] = res
	if ([unitCode, postCode, roleCode].find(item => item !== '200')) return

	unitTree.value = unitData
	postTree.value = postRecords
	roleTree.value = roleRecords
}

/* 添加/修改用户 */
// 提交用户数据
const postUserData = async () => {
	const { code } = await postUserAOUApi({
		...userForm,
	})
	if (code !== '200') return

	ElMessage({
		type: 'success',
		message: userForm.id ? '修改角色成功~' : '添加角色成功~'
	})
	dialogVisible.value = false

	// 通知父组件
	emits('userSuccess')
}
// 点击确认按钮
const onSubmit = () => {
	postUserData()
}

// 监视 dialogVisible
watch(dialogVisible, () => {
	if (dialogVisible.value) {
		if (props.userId) {
			getUserGetData()
		} else {
			Object.assign(userForm, userFormValue())
		}
	}
})
onMounted(() => {
	getTreeData()
})
</script>

<style lang="scss" scoped>
.user-editor-form {
	:deep(.inline) {
		display: inline-flex;
		vertical-align: middle;
		width: 50%;
	}

	.treeList {
		padding: 2px;
		width: 100%;
	}
}

.inline {
	display: inline-flex;
	vertical-align: middle;
	width: 50%;
}
</style>